﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class PerkuliahanFormPage : PhoneApplicationPage
    {
        private MataKuliahList matkul;
        private DosenList dosen;
        private DetailMatkul kuliah;

        public string[] thnAjaran = { "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020" };
        private bool firstLoaded;

        public PerkuliahanFormPage()
        {
            InitializeComponent();
            thnAjaranList.ItemsSource = thnAjaran;

            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                firstLoaded = false;
            }
            else
            {
                firstLoaded = true;
                GetMatkulList();
                GetDosenList();
            }
        }

        #region Event Handlers
        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            kuliah = (DetailMatkul)DataContext;
            if (firstLoaded)
            {
                if (kuliah != null)
                {
                    if (dosenList.ItemsSource != null)
                        dosenList.SelectedItem = kuliah.Creator;
                    if (matkulList.ItemsSource != null)
                        matkulList.SelectedItem = kuliah.Matkul;
                    thnAjaranList.SelectedItem = kuliah.TahunAjaran;
                }
                else
                {
                    thnAjaranList.SelectedItem = DateTime.Now.Year.ToString();
                }
            }
        }

        #endregion

        private void GetMatkulList()
        {
            WebClient webClient = new WebClient();

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.VIEW_ACTION_KEY;
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listMatkul_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listMatkul_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }
                matkul = JsonConvert.DeserializeObject<MataKuliahList>(e.Result);
                matkulList.ItemsSource = matkul;
                if (matkulList.ItemsSource != null && kuliah != null)
                    matkulList.SelectedItem = kuliah.Matkul;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void GetDosenList()
        {
            WebClient webClient = new WebClient();

            string url = Config.Instance.DOSEN_SERVICE_URL() + Config.DOSEN_VIEW_ALL_KEY;
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listDosen_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listDosen_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }
                dosen = JsonConvert.DeserializeObject<DosenList>(e.Result);
                dosenList.ItemsSource = dosen;
                if (dosenList.ItemsSource != null)
                    dosenList.SelectedItem = SavedUser.Instance.User.ConvertUser();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void SavePerkuliahan(DetailMatkul data)
        {
            string json = null, url = null;


            if (data.Id == null)
            {
                data.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
                url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.ADD_ACTION_KEY; //create
            }
            else
            {
                url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.UPDATE_ACTION_KEY; //update
            }
            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (kuliah == null || kuliah.Id == null)
                kuliah = new DetailMatkul();
            kuliah.TahunAjaran = (string)thnAjaranList.SelectedItem;
            MataKuliah matkul = ((MataKuliah)matkulList.SelectedItem);

            kuliah.Matkul = matkul;
            SavePerkuliahan(kuliah);
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}